package br.com.brasilprojetos.geometric;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.opengles.GL10;

import android.graphics.PointF;

public class GameEntity {

	/***/
	private int fillMode;
	
	/***/
	private PointF mScale;
	
	/***/
	private float mRotation;
	
	/***/
	private PointF mPosition;
	
	/** The initial vertex definition */
	protected float mVertices[];
		
	/** The buffer holding the vertices */
	private FloatBuffer mVertexBuffer;

	/**
	 * Constructor
	 */
	public GameEntity() {

		this.mRotation = 0;
		this.mPosition = new PointF();
		this.mScale = new PointF(1.0f, 1.0f);
		
		this.setFillMode(GL10.GL_TRIANGLE_FAN);
	}
	
	protected void populateVertice(){
		
		this.mVertices = new float[12];
		
		final float ds = 50;
		this.mVertices[0] = -ds; this.mVertices[1] = -ds; this.mVertices[2] = 0.0f;
		this.mVertices[3] = -ds; this.mVertices[4] = ds; this.mVertices[5] = 0.0f;
		this.mVertices[6] = ds; this.mVertices[7] = ds; this.mVertices[8] = 0.0f;
		this.mVertices[9] = ds; this.mVertices[10] = -ds; this.mVertices[11] = 0.0f;
	}
	
	public void setFillMode(int pFillMode){
		this.fillMode = pFillMode;
	}

	public void setScale(float pX, float pY){
		this.mScale.x = pX;
		this.mScale.y = pY;
	}

	public void setPosition(float pX, float pY){
		this.mPosition.x = pX;
		this.mPosition.y = pY;
	}

	public void setRotation(float pRotation){
		this.mRotation = pRotation;
	}
	
	/***/
	public void draw(GL10 gl) {

		gl.glPushMatrix();

		gl.glTranslatef(this.mPosition.x, this.mPosition.y, 0.0f);
		gl.glScalef(this.mScale.x, this.mScale.y, 1.0f);
		gl.glRotatef(this.mRotation, 0.0f, 0.0f, 1.0f);
		
		//Set the face rotation
		gl.glFrontFace(GL10.GL_CW);
		
		//Point to our vertex buffer
		gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer);
		
		//Enable vertex buffer
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
		
		//Draw the vertices as triangle strip
		gl.glDrawArrays(this.fillMode, 0, mVertices.length / 3);
		
		//Disable the client state before leaving
		gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);

		gl.glPopMatrix();
	}


	/**
	 * Fill the buffer to create the geometric form
	 * */
	public void createBuffer() {
		
		this.populateVertice();
		
		ByteBuffer byteBuf = ByteBuffer.allocateDirect(mVertices.length * 4);
		byteBuf.order(ByteOrder.nativeOrder());
		mVertexBuffer = byteBuf.asFloatBuffer();
		mVertexBuffer.put(mVertices);
		mVertexBuffer.position(0);
	}
}
